package com.springboot.service;

import com.springboot.constant.CommonConstant;
import com.springboot.domain.*;
import com.springboot.dto.TaskAddCaseDTO;
import com.springboot.dto.TaskAddDTO;
import com.springboot.dto.TaskDetailDTO;
import com.springboot.repository.*;
import com.springboot.tools.UUIDTool;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import javax.transaction.Transactional;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class TaskService {
    private TaskRepository taskRepository;
    private FileRepository fileRepository;
    private UserRepository userRepository;
    private BankRepository bankRepository;
    private PersonRepository personRepository;
    private EnterpriseRepository enterpriseRepository;
    private TeamRepository teamRepository;
    private DemandRepository demandRepository;

    @Autowired
    public TaskService(TaskRepository taskRepository, FileRepository fileRepository, UserRepository userRepository, BankRepository bankRepository, PersonRepository personRepository, EnterpriseRepository enterpriseRepository, TeamRepository teamRepository, DemandRepository demandRepository) {
        this.taskRepository = taskRepository;
        this.fileRepository = fileRepository;
        this.userRepository = userRepository;
        this.bankRepository = bankRepository;
        this.personRepository = personRepository;
        this.enterpriseRepository = enterpriseRepository;
        this.teamRepository = teamRepository;
        this.demandRepository = demandRepository;
    }



    public void addTask(TaskAddDTO taskAddDTO, HttpSession session) {
        String creator=session.getAttribute("user").toString();
        BtDemand demand=demandRepository.findOne(taskAddDTO.getDemandId());
        String announcer=demand.getBankId();
        BtTask task=new BtTask();
        BeanUtils.copyProperties(taskAddDTO,task);
        task.setId(UUIDTool.getUuid());
        task.setAnnouncer(announcer);
        task.setCreator(creator);
        task.setAnnoRead(CommonConstant.UNREAD);
        task.setReceRead(CommonConstant.UNREAD);
        task.setCreateTime(new Date());
        task.setStatus(CommonConstant.UNCONFIRM);
        task.setDemand(demand);
        taskRepository.save(task);
    }

    public TaskDetailDTO findTask(String id,String userId) {
        BtTask task = taskRepository.findOne(id);
        //获取需求
        TaskDetailDTO taskDetailDTO = taskRepository.findTaskById(id);
        //获取发布者信息
        BtBank btBank = bankRepository.findOne(task.getAnnouncer());
        taskDetailDTO.setAnnouncerId(btBank.getId());
        taskDetailDTO.setAnnouncerName(btBank.getName());
        //获取接收者信息
        BtUser u = userRepository.findByUserId(task.getReceiver());
        if(u.getUserType().equals(CommonConstant.USER_PERSON)){
            BtPerson person = personRepository.findOne(u.getUserId());
            taskDetailDTO.setReceiverId(person.getId());
            taskDetailDTO.setReceiverName(person.getName());
        }else if(u.getUserType().equals(CommonConstant.USER_ENTERPRISE)){
            BtEnterprise enterprise = enterpriseRepository.findOne(u.getUserId());
            taskDetailDTO.setReceiverId(enterprise.getId());
            taskDetailDTO.setReceiverName(enterprise.getName());
        }
        //获取文件信息
        List<BtFile> demandFiles = fileRepository.findByUserId(taskDetailDTO.getDemandId());
        taskDetailDTO.setDemandFiles(demandFiles);
        //获取提交解决方案的文件
        List<BtFile> caseFile=fileRepository.findByUserId(id);
        taskDetailDTO.setCaseFiles(caseFile);
        //获取当前用户类型，设置发布者或者接收者读取状态
        BtUser user = userRepository.findByUserId(userId);
        if (user.getUserType().equals(CommonConstant.USER_BANK)){
            taskRepository.updateAnnoRead(id,CommonConstant.READ);
        }else {
            taskRepository.updateReceRead(id,CommonConstant.READ);
        }
        return taskDetailDTO;
    }

    public String assureTask(String id, String userId) {
        String tip = null;
        //获取工单
        BtTask task = taskRepository.findOne(id);
        if (userId.equals(task.getReceiver()) && task.getStatus() == CommonConstant.UNCONFIRM){
            task.setStatus(CommonConstant.CONFIRMING);
            taskRepository.save(task);
        }else if (userId.equals(task.getAnnouncer()) && task.getStatus() == CommonConstant.CONFIRMING){
            //如果接收者为个人，则新增团队记录
            BtUser u =userRepository.findByUserId(task.getReceiver());
            if(u.getUserType().equals(CommonConstant.USER_PERSON)){
                BtTeam team = new BtTeam();
                team.setCreateTime(new Date());
                team.setDemand(demandRepository.findOne(task.getDemand().getId()));
                team.setId(UUIDTool.getUuid());
                team.setUserId(task.getReceiver());
                team.setRole(CommonConstant.ROLE_ADMIN);
                teamRepository.save(team);
            }
            //关闭同需求的其他工单
            taskRepository.closeByDemand(task.getDemand(),CommonConstant.CLOSE);

            //保存taskId,修改签约状态
            BtDemand demand = demandRepository.findOne(task.getDemand().getId());
            demand.setTaskId(id);
            demand.setStatus(CommonConstant.SIGNED);
            demandRepository.save(demand);

            //保存task
            task.setStatus(CommonConstant.CONFIRM);
            taskRepository.save(task);
        }else {
            tip = "error";
        }
        return tip;
    }

    public void taskAddCase(TaskAddCaseDTO taskAddCaseDTO) {
        String taskId=taskAddCaseDTO.getTaskId();
        List<String> fileIds=taskAddCaseDTO.getFileIds();
        BtTask task=taskRepository.findOne(taskId);
        for(String fileId:fileIds){
            fileRepository.update(taskId,fileId);
        }
        String file=getStr(fileIds);
        task.setFileIds(file);
        taskRepository.save(task);
    }


    public String getStr(List<String> strList) {
        String resultStr = "";
        if (strList != null && strList.size() > 0) {
            for (int i = 0; i < strList.size(); i++) {
                resultStr = resultStr + strList.get(i) + ',';
            }
            resultStr = resultStr.substring(0, resultStr.length() - 1);
        }
        return resultStr;
    }

}
